from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection
from random import randint
import logging

from meiduo_mall.utils.response_code import RETCODE
from verifications.libs.captcha.captcha import captcha
from verifications.constants import IMAGE_CODE_REDIS_EXPIRES, SEND_SMS_TEMPLATE_ID, SMS_CODE_REDIS_EXPIRES, \
    SEND_SMS_CODE_INTERVAL
from verifications.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.

# 创建日志输出器
mylogger = logging.getLogger("django")


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """

        :param request:
        :param uuid: 通用唯一标识码，用于唯一标识该图形验证码属于那个用户的
        :return: image/jpg
        """
        # 接收参数
        # 校验参数
        # 实现主体业务逻辑：生成、保存、响应图形验证码
        # 生成图形验证码
        text, image = captcha.generate_captcha()

        # 保存图形验证码
        redis_conn = get_redis_connection("verify_code")
        # redis_conn.setex("key","time","value")
        # redis_conn.setex("img_%s" % uuid, time=5 * 60, value=text)
        redis_conn.setex("img_%s" % uuid, time=IMAGE_CODE_REDIS_EXPIRES, value=text)

        # 响应图形验证码结果
        return http.HttpResponse(image, content_type="image/jpg")


class SMSCodeView(View):
    """短信验证码"""

    def get(self, request, mobile):
        """

        :param request:
        :param mobile: 手机号
        :return: JSON
        """
        # 接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        # 校验参数
        if not all([image_code_client, uuid]):
            return http.HttpResponseForbidden("缺少比传参数")

        # 创建连接redis的对象
        redis_conn = get_redis_connection("verify_code")

        # 提取发送短信验证码的标记
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        # 判断用户是否频繁发送短信验证码
        if send_flag:
            # 响应错误提示信息
            return http.JsonResponse({"code": RETCODE.THROTTLINGERR, "errmsg": "发送短信过于频繁"})

        # 实现业务逻辑
        # 提取图形验证码
        # 删除图形验证码
        # 对比图形验证码

        image_code_server = redis_conn.get("img_%s" % uuid)
        if image_code_server is None:
            return http.JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "图形验证码已失效"})
        redis_conn.delete("img_%s" % uuid)
        # 将bytes转成字符串再比较
        image_code_server = image_code_server.decode()
        if not image_code_client.lower() == image_code_server.lower():  # 转小写再比较
            return http.JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "输入图形验证码有误"})

        # 生成短信验证码：随机6位数字 000007
        # sms_code = str(randint(100000, 999999))
        sms_code = "%06d" % randint(0, 999999)
        mylogger.info("短信验证码sms_code： %s" % sms_code)  # 手动输出日志，记录短信验证码
        # # 保存短信验证码
        # redis_conn.setex("sms_%s" % mobile, time=SMS_CODE_REDIS_EXPIRES, value=sms_code)
        # # 保存发送短信验证码的标记
        # redis_conn.setex("send_flag_%s" % mobile, SEND_SMS_CODE_INTERVAL, 1)

        # 创建redis管道
        pl = redis_conn.pipeline()
        # 将命令命令添加到队列
        # 保存短信验证码
        pl.setex("sms_%s" % mobile, time=SMS_CODE_REDIS_EXPIRES, value=sms_code)
        # 保存发送短信验证码的标记
        pl.setex("send_flag_%s" % mobile, SEND_SMS_CODE_INTERVAL, 1)
        # 执行命令
        pl.execute()


        # 发送短信验证码
        # data = (sms_code, SMS_CODE_REDIS_EXPIRES // 60)
        # result = CCP().send_template_sms(mobile, datas=data, tempId=SEND_SMS_TEMPLATE_ID)
        # 使用Celery发送短信验证码（异步任务）
        # send_sms_code(mobile, sms_code) # 错误写法
        send_sms_code.delay(mobile, sms_code) # 千万不要忘记写delay

        # 响应结果

        # return http.JsonResponse({"code": RETCODE.OK, "errmsg": "OK", "data": result})
        return http.JsonResponse({"code": RETCODE.OK, "errmsg": "发送短信成功"})
